import worker from '@ohos.worker';
import socket from '@ohos.net.socket';
import wifiManager from '@ohos.wifiManager';
import {
  ipToStr,
  ipToHex,
  hexToIp,
  hexIpToDynamicLengthHexIP,
  dynamicLengthHexIPToHexIP
} from '../common/NetWork/AddressUtil';
import { GyroscopeControl, Info } from '../common/RemoteControl/GyroscopeControl';
import { Exchange, OperationType } from './WorkerExchange';

const workerPort = worker.workerPort;

let tcpSocket: socket.TCPSocket = null;
let gyroscope: GyroscopeControl = null;


workerPort.onmessage = (event) => { //event.data是一个Object
  let exchange = Exchange.fromObject(event.data);
  if (exchange != null) { //如果是该类的实例
    switch (exchange.type) { //根据type的值进行不同的操作
      case OperationType.create: //创建socket
        if (tcpSocket == null) {
          tcpSocket = socket.constructTCPSocketInstance();
          let ip = wifiManager.getIpInfo().ipAddress;
          if (ip == 0) {
            workerPort.postMessage("failed");
            return;
          }
          let ipStr = ipToStr(ip); //绑定端口
          tcpSocket.bind({ address: ipStr, port: 10001 }).then((result) => {
            console.info("bind success");
            let pairCode = hexIpToDynamicLengthHexIP(ipToHex(ipStr));
            workerPort.postMessage(pairCode); //将ip和端口返回给主线程
            tcpSocket.on('close', (data) => {
              workerPort.postMessage("stop"); //将关闭的消息返回给主线程
              if (gyroscope != null) {
                gyroscope.close();
              }
              tcpSocket.close();
              tcpSocket = null;
            });
            tcpSocket.on('message', (data) => {
              let infoStr = arrayBufferToString(data.message); //将ArrayBuffer转换为字符串
              let info = Info.fromString(infoStr); //将字符串转换为Info对象
              workerPort.postMessage(info.toObject()); //将Info对象转换为Object对象并返回给主线程
            });
          }, (error) => {
            console.error("bind failed");
            workerPort.postMessage("failed");
          });
        }
        break;
      case OperationType.connect: //连接socket
        if (socket != null) {
          let hexIp = exchange.ip;
          let ip = hexToIp(dynamicLengthHexIPToHexIP(hexIp));
          tcpSocket.connect({ address: { address: ip, port: 10001 } }).then((result) => {
            console.info("connect success");
            workerPort.postMessage("success"); //将连接成功的消息返回给主线程

            //监听关闭事件
            tcpSocket.on('close', (data) => {
              workerPort.postMessage("stop"); //将关闭的消息返回给主线程
              tcpSocket.close();
              if (gyroscope != null) {
                gyroscope.close();
              }
              tcpSocket = null;
            });
          }, (error) => {
            console.error("connect failed");
            workerPort.postMessage("failed"); //将连接失败的消息返回给主线程
          });
        }
        break;
      case OperationType.close:
        if (socket != null) { //关闭
          tcpSocket.close().then((result) => {
            console.info("close success");
            workerPort.postMessage("success");
          }, (error) => {
            console.error("close failed");
            workerPort.postMessage("failed");
          });
          tcpSocket = null;
        }
        break;
      case OperationType.startGyroscope: //开始监听陀螺仪
        if (socket != null) {
          gyroscope = new GyroscopeControl(1e5);
          gyroscope.setCallback((info: Info) => {
            workerPort.postMessage(info.toObject()); //将Info对象转换为Object对象并返回给主线程
          });
        }
        break;
      case OperationType.stopGyroscope: //停止监听陀螺仪
        if (gyroscope != null) {
          gyroscope.close();
          gyroscope = null;
        }
        break;
    }
  }
}

function arrayBufferToString(buffer): string {
  return String.fromCharCode.apply(null, new Uint8Array(buffer))
}